<template>
  <div class="login-container">
    <div class="login-background">
      <div class="bg-overlay"></div>
      <div class="bg-animation">
        <div class="floating-element" v-for="i in 6" :key="i" :style="getFloatingStyle(i)"></div>
      </div>
    </div>
    
    <div class="login-content">
      <div class="login-form-container">
        <!-- Logo和标题 -->
        <div class="login-header">
          <div class="logo">
            <el-icon :size="48" color="#409EFF">
              <OfficeBuilding />
            </el-icon>
          </div>
          <h1 class="title">酒店管理系统</h1>
          <p class="subtitle">Hotel Management System</p>
        </div>
        
        <!-- 登录表单 -->
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          auto-complete="on"
          label-position="left"
        >
          <el-form-item prop="username">
            <el-input
              ref="usernameRef"
              v-model="loginForm.username"
              placeholder="请输入用户名"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
              size="large"
              :prefix-icon="User"
              clearable
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              ref="passwordRef"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              size="large"
              :prefix-icon="Lock"
              @keyup.enter="handleLogin"
            >
              <template #suffix>
                <el-icon class="password-icon" @click="showPassword">
                  <component :is="passwordType === 'password' ? 'View' : 'Hide'" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <!-- 验证码 -->
          <el-form-item prop="captcha" v-if="showCaptcha">
            <div class="captcha-container">
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                size="large"
                :prefix-icon="Key"
                @keyup.enter="handleLogin"
              />
              <div class="captcha-image" @click="refreshCaptcha">
                <img :src="captchaImage" alt="验证码" />
              </div>
            </div>
          </el-form-item>
          
          <!-- 记住密码 -->
          <div class="login-options">
            <el-checkbox v-model="loginForm.rememberMe" size="small">
              记住密码
            </el-checkbox>
            <el-link type="primary" :underline="false" @click="handleForgotPassword">
              忘记密码？
            </el-link>
          </div>
          
          <!-- 登录按钮 -->
          <el-button
            :loading="loading"
            type="primary"
            size="large"
            class="login-button"
            @click.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登录中...</span>
          </el-button>
        </el-form>
        
        <!-- 快速登录 -->
        <div class="quick-login">
          <el-divider>
            <span class="divider-text">快速登录</span>
          </el-divider>
          <div class="quick-login-buttons">
            <el-button
              v-for="account in quickAccounts"
              :key="account.username"
              :type="account.type"
              size="small"
              @click="quickLogin(account)"
            >
              {{ account.label }}
            </el-button>
          </div>
        </div>
        
        <!-- 版权信息 -->
        <div class="copyright">
          <p>&copy; 2023 酒店管理系统. All rights reserved.</p>
          <p>Version 1.0.0</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Lock, Key, View, Hide, OfficeBuilding } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { getValidateCode } from '@/api/auth'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref()
const usernameRef = ref()
const passwordRef = ref()

// 响应式数据
const loading = ref(false)
const passwordType = ref('password')
const showCaptcha = ref(false)
const captchaImage = ref('')

// 登录表单数据
const loginForm = reactive({
  username: 'admin',
  password: 'admin123',
  captcha: '',
  rememberMe: true
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码长度为 4 位', trigger: 'blur' }
  ]
}

// 快速登录账号
const quickAccounts = [
  { username: 'admin', password: 'admin123', label: '管理员', type: 'primary' },
  { username: 'receptionist', password: 'receptionist123', label: '前台', type: 'success' },
  { username: 'housekeeper', password: 'housekeeper123', label: '客房', type: 'warning' },
  { username: 'finance', password: 'finance123', label: '财务', type: 'info' }
]

// 显示/隐藏密码
const showPassword = () => {
  passwordType.value = passwordType.value === 'password' ? 'text' : 'password'
  nextTick(() => {
    passwordRef.value.focus()
  })
}

// 刷新验证码
const refreshCaptcha = async () => {
  try {
    const response = await getValidateCode()
    captchaImage.value = response.data
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    await userStore.login(loginForm)
    
    ElMessage.success('登录成功')
    
    // 跳转到目标页面
    const redirect = route.query.redirect || '/'
    await router.push(redirect)
    
  } catch (error) {
    ElMessage.error(error.message || '登录失败')
    
    // 登录失败后显示验证码
    if (!showCaptcha.value) {
      showCaptcha.value = true
      await refreshCaptcha()
    } else {
      await refreshCaptcha()
    }
  } finally {
    loading.value = false
  }
}

// 快速登录
const quickLogin = (account) => {
  loginForm.username = account.username
  loginForm.password = account.password
  handleLogin()
}

// 忘记密码
const handleForgotPassword = () => {
  ElMessageBox.alert(
    '请联系系统管理员重置密码',
    '忘记密码',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}

// 获取浮动元素样式
const getFloatingStyle = (index) => {
  const size = Math.random() * 60 + 20
  const left = Math.random() * 100
  const animationDelay = Math.random() * 20
  const animationDuration = Math.random() * 10 + 10
  
  return {
    width: `${size}px`,
    height: `${size}px`,
    left: `${left}%`,
    animationDelay: `${animationDelay}s`,
    animationDuration: `${animationDuration}s`
  }
}

// 组件挂载
onMounted(() => {
  // 自动聚焦到用户名输入框
  nextTick(() => {
    if (loginForm.username === '') {
      usernameRef.value?.focus()
    } else {
      passwordRef.value?.focus()
    }
  })
  
  // 从localStorage恢复记住的用户名
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    loginForm.username = rememberedUsername
    loginForm.rememberMe = true
  }
})

// 监听记住密码变化
watch(
  () => loginForm.rememberMe,
  (newVal) => {
    if (newVal) {
      localStorage.setItem('rememberedUsername', loginForm.username)
    } else {
      localStorage.removeItem('rememberedUsername')
    }
  }
)
</script>

<style lang="scss" scoped>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  
  .bg-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.1);
  }
  
  .bg-animation {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    
    .floating-element {
      position: absolute;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 50%;
      animation: float 20s infinite linear;
      
      @keyframes float {
        0% {
          transform: translateY(100vh) rotate(0deg);
          opacity: 0;
        }
        10% {
          opacity: 1;
        }
        90% {
          opacity: 1;
        }
        100% {
          transform: translateY(-100px) rotate(360deg);
          opacity: 0;
        }
      }
    }
  }
}

.login-content {
  position: relative;
  z-index: 10;
  width: 100%;
  max-width: 400px;
  padding: 0 20px;
}

.login-form-container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
  
  .logo {
    margin-bottom: 16px;
  }
  
  .title {
    font-size: 28px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 8px;
  }
  
  .subtitle {
    font-size: 14px;
    color: #7f8c8d;
    margin: 0;
  }
}

.login-form {
  .el-form-item {
    margin-bottom: 24px;
    
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      
      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
  }
}

.captcha-container {
  display: flex;
  gap: 12px;
  
  .el-input {
    flex: 1;
  }
  
  .captcha-image {
    width: 100px;
    height: 40px;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
    border: 1px solid var(--el-border-color);
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

.password-icon {
  cursor: pointer;
  color: var(--el-text-color-placeholder);
  transition: color 0.3s ease;
  
  &:hover {
    color: var(--el-color-primary);
  }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  .el-checkbox {
    :deep(.el-checkbox__label) {
      font-size: 14px;
      color: var(--el-text-color-regular);
    }
  }
  
  .el-link {
    font-size: 14px;
  }
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(135deg, #409EFF 0%, #3a8ee6 100%);
  border: none;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.quick-login {
  margin-top: 32px;
  
  .divider-text {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
  }
  
  .quick-login-buttons {
    display: flex;
    gap: 8px;
    margin-top: 16px;
    
    .el-button {
      flex: 1;
      font-size: 12px;
    }
  }
}

.copyright {
  text-align: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid var(--el-border-color-lighter);
  
  p {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
    margin: 4px 0;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-form-container {
    padding: 24px;
    margin: 0 16px;
  }
  
  .login-header .title {
    font-size: 24px;
  }
  
  .quick-login-buttons {
    flex-wrap: wrap;
    
    .el-button {
      flex: 1 1 calc(50% - 4px);
    }
  }
}

// 暗色模式适配
.dark {
  .login-form-container {
    background: rgba(0, 0, 0, 0.8);
    border: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .login-header .title {
    color: var(--el-text-color-primary);
  }
}
</style>